package cn.tedu.sp02.controller;

import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.tedu.pojo.Item;
import cn.tedu.service.ItemService;
import cn.tedu.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;

//@Controller
@Slf4j
@RestController //@Controller+@ResponseBody
public class ItemController {
	
	@Autowired
	private ItemService itemService;
	
	@Value("${server.port}")
	private int port;
	
	//@RequestMapping(method = "get")
	@GetMapping("/{orderId}")
	//@ResponseBody
	public JsonResult<List<Item>> getItems(@PathVariable String orderId){
		log.info("orderId:"+orderId);
		//模拟超时
		if(Math.random()<0.6) {
			//超时时长：[0,5000)
			int time = new Random().nextInt(5000);
			System.out.println("延迟时间："+time);
			try {
				Thread.sleep(time);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		List<Item> items = itemService.getItems(orderId);
		return JsonResult.ok(items).msg("port:"+port);
	}
	
	@PostMapping("/decreaseNumber")
	public JsonResult decreseNumbers(@RequestBody List<Item> items) {
		itemService.decreaseNumbers(items);
		return JsonResult.ok();
	}
}
